package algorithms;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class GrayScaleAsBilevel implements BilevelAlgorithm
{
	
	@Override
	public BufferedImage toBilevelImage(File original) throws IOException {

		int dimensionWidth = 0;
		int dimensionHeigth = 0;
		if(original.getName().contains("_cb_")){
			dimensionWidth = 128;
			dimensionHeigth = 32;
		}
		if(original.getName().contains("_cr_")){
			dimensionWidth = 512;
			dimensionHeigth = 84;
		}
		if(original.getName().contains("_dct_")){
			dimensionWidth = 512;
			dimensionHeigth = 42;
		}
		if(original.getName().contains("_ko_")){
			dimensionWidth = 240;
			dimensionHeigth = 16;
		}
		if(original.getName().contains("_lg_")){
			dimensionWidth = 512;
			dimensionHeigth = 20;
		}
		if(original.getName().contains("_qsw_")){
			dimensionWidth = 512;
			dimensionHeigth = 20;
		}
		
		BufferedImage grayscaleImg = ImageIO.read(original);
		Raster grayscaleData = grayscaleImg.getData();
		
		BufferedImage binaryImg = new BufferedImage(dimensionWidth, dimensionHeigth, BufferedImage.TYPE_BYTE_BINARY);
		WritableRaster bilevelData = binaryImg.getRaster();
		
		int curValue = 0;

		for (int width = 0; width < grayscaleData.getWidth(); width++) {
			for (int heigth = 0; heigth < grayscaleData.getHeight(); heigth++) {		
				curValue = grayscaleData.getSample(width, heigth, 0);
				for (int i = 128, pixel = 0; i != 0 ; i/=2, pixel++) {
					int asInt = curValue & i;
					if (asInt != 0) {
						if((int)((width*8)/dimensionWidth) < dimensionHeigth) bilevelData.setSample(((width*8)%dimensionWidth)+pixel, (int)((width*8)/dimensionWidth), 0, 255);
					}
					else {
						if((int)((width*8)/dimensionWidth) < dimensionHeigth) bilevelData.setSample(((width*8)%dimensionWidth)+pixel, (int)((width*8)/dimensionWidth), 0, 0);
					}
				}
			}
		}
		return binaryImg;
	}

}
